package com.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Collection;

@WebServlet(name = "FileServlet",urlPatterns = {"/FileServlet"})
@MultipartConfig
public class FileServlet extends HttpServlet {

	//处理文件上传
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		//通过Servlet 3.0 获取文件上传所需要使用的 Part

//	 Collection<Part> parts =  request.getParts();

		Part part = request.getPart("ufile");//文件域的namg名称的值
		//获取上传文件的名称
		String fileName = getFileName(part); //上传到服务器的文件名称
		//将文件上传到指定的目录
		String uploadFilePath = request.getSession().getServletContext().getRealPath("upload/");//上传的位置
		String path = uploadFilePath + File.separator + fileName;
		System.out.println(path);
		part.write(path);

		response.sendRedirect("result.jsp");
	}

	//获取上传文件的名称
	private String extractFileName(Part part) {
		String contentDisp = part.getHeader("content-disposition");
		System.out.println("contentDisp:"+contentDisp);
		String[] items = contentDisp.split(";");
		for (String s : items) {
			if (s.trim().startsWith("filename")) {
				return s.substring(s.indexOf("=") + 2, s.length()-1);
			}
		}
		return "";
	}

	private String getFileName(Part part){
		String fileName = extractFileName(part); //C:\Users\Elle\Desktop\a.txt

		return fileName.substring(fileName.lastIndexOf(File.separator)+1);
	}


}
